/**
 * 报告相关 API
 */
import request, { ResponseData } from '@/utils/request';
import { AssessmentDetail } from './assessment';

// 图表数据
export interface ChartData {
  radar_chart: {
    dimensions: string[];
    scores: number[];
    max_score: number;
  };
  bar_chart: {
    categories: string[];
    values: number[];
  };
  score_gauge: {
    overall_score: number;
    max_score: number;
    grade: string;
  };
  issues_by_type: {
    labels: string[];
    values: number[];
  };
  issues_by_severity: {
    labels: string[];
    values: number[];
  };
}

// 报告统计
export interface ReportStatistics {
  total_issues: number;
  critical_issues: number;
  major_issues: number;
  minor_issues: number;
}

// 完整报告
export interface AssessmentReport {
  assessment: AssessmentDetail;
  record: {
    id: string;
    patient_name: string;
    patient_age?: number;
    patient_gender?: string;
    department?: string;
    visit_date?: string;
    chief_complaint?: string;
    diagnosis?: string[];
    doctor_name?: string;
    created_at: string;
  };
  statistics: ReportStatistics;
  charts_data: ChartData;
}

/**
 * 获取评估报告
 */
export const getAssessmentReport = (recordId: string) => {
  return request.get<ResponseData<AssessmentReport>>(`/reports/${recordId}`);
};

/**
 * 获取API基础URL
 */
const getApiBaseUrl = () => {
  return import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000/api/v1';
};

/**
 * 导出报告为 PDF
 */
export const exportReportToPDF = async (recordId: string) => {
  const apiBaseUrl = getApiBaseUrl();
  const response = await fetch(`${apiBaseUrl}/reports/${recordId}/export/pdf`, {
    method: 'GET',
    headers: {
      'Content-Type': 'application/pdf',
    },
  });

  if (!response.ok) {
    throw new Error('导出PDF失败');
  }

  const blob = await response.blob();
  const url = window.URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = `report_${recordId}.pdf`;
  document.body.appendChild(a);
  a.click();
  window.URL.revokeObjectURL(url);
  document.body.removeChild(a);
};

/**
 * 导出报告为 Excel
 */
export const exportReportToExcel = async (recordId: string) => {
  const apiBaseUrl = getApiBaseUrl();
  const response = await fetch(`${apiBaseUrl}/reports/${recordId}/export/excel`, {
    method: 'GET',
    headers: {
      'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    },
  });

  if (!response.ok) {
    throw new Error('导出Excel失败');
  }

  const blob = await response.blob();
  const url = window.URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = `report_${recordId}.xlsx`;
  document.body.appendChild(a);
  a.click();
  window.URL.revokeObjectURL(url);
  document.body.removeChild(a);
};

